<template>
	<view class="contain">
		<u-navbar title="预约报名" :autoBack="false" :placeholder='true' :isBack='false' :titleStyle="{fontWeight:700}">
		</u-navbar>
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<u--form v-if="showForm && !whether" labelPosition="left" :model="model1" :rules="rules" ref="uForm"
			:labelWidth='100'>
			<u-form-item label="宝贝姓名:" prop="userInfo.studentName" borderBottom ref="item1" required>
				<u--input v-model="model1.userInfo.studentName" border="none" placeholder="请填写宝贝姓名"></u--input>
			</u-form-item>
			<u-form-item label="宝贝性别:" prop="userInfo.studentSex" borderBottom @click="showSex = true" ref="item1"
				required>
				<u--input v-model="model1.userInfo.studentSex" disabled disabledColor="#ffffff" placeholder="请选择性别"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>

			<u-form-item label="出生日期:" prop="userInfo.studentBirthday" borderBottom @click="openDate('start')"
				ref="item1" required>
				<view class=""><u--input v-model="model1.userInfo.studentBirthday" disabled disabledColor="#ffffff"
						placeholder="请选择出生日期" border="none"></u--input></view>
			</u-form-item>
			<u-form-item label="宝贝身份证号:" prop="userInfo.cardId" borderBottom ref="item1" required>
				<u--input v-model="model1.userInfo.cardId" border="none" placeholder="请填写宝贝身份证号"></u--input>
			</u-form-item>
			<u-form-item label="家长姓名:" prop="userInfo.parentName" borderBottom ref="item1" required>
				<u--input v-model="model1.userInfo.parentName" border="none" placeholder="请填写家长姓名"></u--input>
			</u-form-item>
			<u-form-item label="家长手机号:" prop="userInfo.parentMobile" borderBottom ref="item1" required>
				<u--input v-model="model1.userInfo.parentMobile" border="none" placeholder="请填写家长手机号"></u--input>
			</u-form-item>
			<!-- <u-form-item label="宝贝照片:" borderBottom ref="item1">
				<u-upload :previewFullImage="true" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic"
					name="1" :maxCount='1'></u-upload>
			</u-form-item> -->
			<text class="" style="color: red;">
				*请根据预约报名的要求上传附件，否则影响报名结果
			</text>
			<u-form-item label="上传附件:" borderBottom ref="item1" required>

				<u-upload :previewFullImage="true" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic"
					name="1" multiple></u-upload>
			</u-form-item>
			<!-- <button class="btn" style="margin-top: 20px;" open-type="getPhoneNumber"
				@getphonenumber="getPhoneNumber">提交</button> -->
			<button class="btn submit" @click="submit">提交</button>
		</u--form>
		<view v-show='!showForm' class="" style="text-align: center;margin-top: 20rpx;">
			<image class="submitImg" src="@/static/sub.png" alt="">
				<view style="margin-top: 30rpx;font-size: 20px;">提交成功</view>
		</view>
		<view v-show='whether' class="" style="text-align: center;margin-top: 20rpx;">
			<uni-icons type="clear" size="90" color="red"></uni-icons>
			<view style="margin-top: 30rpx;font-size: 20px;">预约报名时间已截止！</view>
		</view>
		<u-action-sheet :show="showSex" :actions="actions" title="请选择性别" @close="showSex = false" @select="sexSelect"
			:round='10'>
		</u-action-sheet>
		<u-datetime-picker mode='date' :show="showDate" @cancel="showDate = false" @confirm="selectDate"
			v-model="dateTime"></u-datetime-picker>
	</view>
</template>

<script>
	// import {
	// 	saveRegistration,
	// 	verifyRegistration
	// } from '@/api/AppointmentRegistration.js'
	var checkCode = function(val) {
		var p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
		var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
		var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
		var code = val.substring(17);
		if (p.test(val)) {
			var sum = 0;
			for (var i = 0; i < 17; i++) {
				sum += val[i] * factor[i];
			}
			if (parity[sum % 11] == code.toUpperCase()) {
				return true;
			}
		}
		return false;
	}
	var checkDate = function(val) {
		var pattern = /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/;
		if (pattern.test(val)) {
			var year = val.substring(0, 4);
			var month = val.substring(4, 6);
			var date = val.substring(6, 8);
			var date2 = new Date(year + "-" + month + "-" + date);
			if (date2 && date2.getMonth() == (parseInt(month) - 1)) {
				return true;
			}
		}
		return false;
	};
	var checkProv = function(val) {
		var pattern = /^[1-9][0-9]/;
		var provs = {
			11: "北京",
			12: "天津",
			13: "河北",
			14: "山西",
			15: "内蒙古",
			21: "辽宁",
			22: "吉林",
			23: "黑龙江 ",
			31: "上海",
			32: "江苏",
			33: "浙江",
			34: "安徽",
			35: "福建",
			36: "江西",
			37: "山东",
			41: "河南",
			42: "湖北 ",
			43: "湖南",
			44: "广东",
			45: "广西",
			46: "海南",
			50: "重庆",
			51: "四川",
			52: "贵州",
			53: "云南",
			54: "西藏 ",
			61: "陕西",
			62: "甘肃",
			63: "青海",
			64: "宁夏",
			65: "新疆",
			71: "台湾",
			81: "香港",
			82: "澳门"
		};
		if (pattern.test(val)) {
			if (provs[val]) {
				return true;
			}
		}
		return false;
	};
	var checkID = function(val) {
		if (checkCode(val)) {
			var date = val.substring(6, 14);
			if (checkDate(date)) {
				if (checkProv(val.substring(0, 2))) {
					return true;
				}
			}
		}
		return false;
	};
	export default {
		options: {
			styleIsolation: 'shared'
		}, //解决/deep/不生效**
		data() {
			return {
				showSex: false,
				model1: {
					userInfo: {
						studentName: '',
						studentSex: '',
						studentBirthday: '',
						parentName: '',
						parentMobile: '',
						cardId: ''
					},
				},
				actions: [{
						name: '男',
					},
					{
						name: '女',
					},

				],
				fileList1: [], //上传图片
				dateTime: Number(new Date()),
				rules: {
					'userInfo.studentName': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'userInfo.studentSex': {
						type: 'string',
						max: 1,
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					},
					'userInfo.studentBirthday': {
						type: 'string',
						required: true,
						message: '请选择出生日期',
						trigger: ['blur', 'change']
					},
					'userInfo.parentMobile': [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],

					'userInfo.cardId': [{
							required: true,
							message: '请输入宝贝身份证号',
							trigger: ['change', 'blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								console.log('返回校验', checkID(value))
								return checkID(value)
							},
							message: '身份证格式不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],
					'userInfo.parentName': {
						type: 'string',
						required: true,
						message: '请填写家长姓名',
						trigger: ['blur', 'change']
					},
				},
				radio: '',
				switchVal: false,
				showDate: false,
				tenantId: '',
				showForm: true,
				openId: '',
				whether: false,
				time: '',
				jsonUrl: {},
				optionse: '',
				qrUrl: ''
			};
		},
		watch: {
			'model1.userInfo.cardId': function(va) {
				
				if (uni.$u.test.idCard(va)) {
					uni.request({
						url: this.$config.URL + 'api/app/registration/v1/verify', //仅为示例，并非真实接口地址。
						data: {
							cardId: va,
							tenantId: this.tenantId
						},
						header: {
							"content-type": "application/json"
						},
						success: (res) => {
							console.log(res.data.data);
							if (res.data.data) {
								this.$api.showTip('该宝贝已经提交过报名信息，请勿重复提交')
							}
						}
					});

				}

			}
		},
		onLoad(option) {
			this.tenantId=3
			this.optionse = JSON.stringify(option);
			if (option.q && option.q != "undefined") {
				this.qrUrl = decodeURIComponent(option.q)
				this.tenantId = this.getQueryString(this.qrUrl, 'tenantId');
				this.time = this.getQueryString(this.qrUrl, 'time')
				let timeTamp = this.today_time()
				this.time1 = timeTamp
				// 报名时间
				this.whether = this.comparenewDate(this.time1, this.time)

			}
			this.get()
		},
		methods: {
			today_time() {
				var myDate = new Date;
				var year = myDate.getFullYear(); //获取当前年
				var mon = myDate.getMonth() + 1 < 10 ? "0" + (myDate.getMonth() + 1) : myDate.getMonth() + 1; //获取当前月
				var date = myDate.getDate() < 10 ? "0" + myDate.getDate() : myDate.getDate(); //获取当前日
				return year + "-" + mon + "-" + date;
			},
			comparenewDate(d1, d2) {
				return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
			},
			//解析链接地址
			getQueryString(url, variable) {

				let query = url.substring(1);
				let vars = query.split("&");
				for (let i = 0; i < vars.length; i++) {
					let pair = vars[i].split("=");
					if (pair[0] == variable) {

						return pair[1];
					}
				}

				return (false);
			},

			get() {
				uni.login({
					provider: 'weixin',
					success: res => {
						console.log('code2222222', res.code);
						uni.request({
							url: this.$config.URL + "api/admin/wx/user/wxd0e1c1ccdb79b002/openId/",
							method: "GET",
							data: {
								code: res.code
								// encryptedData: e.detail.encryptedData,
								// iv: e.detail.iv,
								// sessionKey: this.session_key,
								// openId: this.openId,
							},
							success: (ress) => {
								console.log('ressssss', ress.data)
								this.openId = ress.data
								// this.form.phone=res.data.phoneNumber
							}
						})
					}
				});
			},
			getPhoneNumber(e) {
				let that = this;
				console.log('获取手机号', e.detail)
				console.log(e.detail.errMsg) // 判断用户是否允许获取手机号
				console.log(e.detail.iv) // 参数 iv
				console.log(e.detail.encryptedData) // 参数encryptedData
				if (e.detail.errMsg == "getPhoneNumber:ok") { // 用户允许或去手机号

				}
			},
			// 验证是否重复报名

			submit() {
				this.$refs.uForm.validate().then(res => {
					if (!this.fileList1.length) {
						this.$api.showTip('请上传附件')
						return
					}
					// 获取提交数据
					console.log('thisssssss', this.model1.userInfo)
					this.model1.userInfo.fileImg = JSON.stringify(this.fileList1.map(it => it.url));
					this.model1.userInfo.status = 0;
					this.model1.userInfo.tenantId = this.tenantId;
					this.model1.userInfo.userOpenId = this.openId;
					uni.showLoading({
						title: '正在提交中...',
						mask: true
					})
					uni.request({
						url: this.$config.URL + 'api/app/registration/v1/saveRegistration', //
						data: this.model1.userInfo,
						method: 'POST',
						header: {
							"content-type": "application/json"
						},
						success: (res) => {
							uni.hideLoading()
							console.log(res.data);
							if (res.data.code == '0') {
								this.$api.showTip('报名信息提交成功')
								wx.showModal({
									title: '提示',
									content: '请授权开通预约成功提醒',
									showCancel: true,
									success: function(ress) {
										if (ress.confirm) {
											wx.requestSubscribeMessage({ // 调起消息订阅界面
												tmplIds: [
													'jJoI7yeEqyBQvwet1QJ2g7CoFrVu65fSgwv_wJVQiY8'
												],
												success(res) {
													console.log('订阅消息 成功 ');
													console.log(res);
												},
												fail(er) {
													console.log("订阅消息 失败 ");
													console.log(er);
												}
											})

										}
									}
								})
								this.$forceUpdate()
								this.showForm = false
							} else {
								this.$api.showTip(res.data.msg)
							}
						}
					});
				}).catch(errors => {

				})
			},
			openDate() {
				this.showDate = true;
			},
			selectDate(d) {
				console.log('dddddddddd', d)
				this.model1.userInfo.studentBirthday = this.format(d.value);
				this.showDate = false;
			},
			sexSelect(e) {
				this.model1.userInfo.studentSex = e.name
				this.$refs.uForm.validateField('userInfo.studentSex')
			},
			// 删除图片
			deletePic(event) {
				console.log('event', event)
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				console.log('选择图片', event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map(item => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},

			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$config.URL + 'api/app/sysFile/v1/save', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: res => {
							resolve(JSON.parse(res.data).url);

						}
					});
				});
			},

			format(shijianchuo) {
				//shijianchuo是整数，否则要parseInt转换
				var time = new Date(shijianchuo);
				var y = time.getFullYear();
				var m = time.getMonth() + 1;
				var d = time.getDate();
				var h = time.getHours();
				var mm = time.getMinutes();
				var s = time.getSeconds();
				return y + '-' + this.add0(m) + '-' + this.add0(d)
			},
			add0(m) {
				return m < 10 ? '0' + m : m;
			},
		},
		onReady() {
			
				this.$refs.uForm.setRules(this.rules)
			
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		},
	};
</script>
<style lang="scss" scoped>
	page {
		width: 100%;
		height: 100% !important;
		background-color: #fff;
	}

	.contain {
		position: relative;
		top: 0;
		left: 0;
		background-color: #fff;
		// background: url('../../../static/1.jpeg');
		// background-size: auto 100%;
		padding: 20rpx 40rpx;

	}

	/deep/.u-form-item {
		margin-bottom: 15rpx;
	}

	.submit {
		border: 0;
		margin-bottom: 40rpx;
	}

	/deep/ .u-popup__content {
		padding-bottom: 20px !important;
	}

	.submitImg {
		width: 100px;
		height: 100px;
	}
</style>